package com.aclyyx.mi.display.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class Controller {
	
	public final static String CMD_EXIT = "EXIT";
	public final static String CMD_SET_PARAM = "SET";
	public final static String CMD_START_SERVER = "START";
	public final static String CMD_GO = "GO";
	public final static String CMD_IP = "IP";
	public final static String CMD_PORT = "PORT";
	public final static String CMD_HELP1 = "HELP";
	public final static String CMD_HELP2 = "?";
	public final static String CMD_STOP = "STOP";
	public final static String CMD_NUM = "N";
	
	private Param param;
	private List<Connect> connects;
	private ServerThread serverThread;
	private ComputeThread computeThread;
	
	public Controller(Param param) {
		this.param = param;
	}

	public void run() {
		InputStreamReader stdin	= new InputStreamReader(System.in);
		BufferedReader reader	= new BufferedReader(stdin);
		
		String line;
		
		try {
			while (true) {
				System.out.print(":");
				line = reader.readLine().trim();
				if (CMD_EXIT.equalsIgnoreCase(line)) {
					exit();
				} else if (CMD_SET_PARAM.equalsIgnoreCase(line)) {
					setParam(reader);
				} else if (CMD_START_SERVER.equalsIgnoreCase(line)) {
					startServer();
				} else if (CMD_GO.equalsIgnoreCase(line)) {
					go();
				} else if (CMD_IP.equalsIgnoreCase(line)) {
					showIP();
				} else if (CMD_PORT.equalsIgnoreCase(line)) {
					port(reader);
				} else if (CMD_HELP1.equalsIgnoreCase(line) || CMD_HELP2.equalsIgnoreCase(line)) {
					showHelp();
				} else if (CMD_STOP.equalsIgnoreCase(line)) {
					stopServer();
				} else if (CMD_NUM.equalsIgnoreCase(line)) {
					num();
				} else if ("".equalsIgnoreCase(line)) {
				} else {
					System.out.println("命令无效");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void port(BufferedReader reader) {

		if (serverThread != null) {
			System.out.println("服务已经启动");
		} else {
			System.out.println("请输入服务端口号：");
			System.out.print(">");
			try {
				String line = reader.readLine().trim();
				param.setPort(Integer.valueOf(line));
				System.out.println("服务端口号设置成功");
			} catch (Exception e) {
				System.out.println("服务端口号设置失败");
			}
		}
	}
	
	private void num() {

		if (serverThread != null) {
			System.out.println("当前客户端数量：" + connects.size());
		} else {
			System.out.println("服务尚未启动");
		}
	}
	
	private void setParam(BufferedReader reader) throws Exception {
		String line;
		if (serverThread == null) {

//			/** 手机屏幕分辨率类型 **/
//			private String dpx;
			String[] ss = new String[]{
					Param.DPX_480X854,
					Param.DPX_480X800,
					Param.DPX_320X480,
					Param.DPX_240X320
			};
			System.out.println("请输入手机屏幕分辨率类型");
			System.out.println("0.480×854");
			System.out.println("1.480×800");
			System.out.println("2.320×480");
			System.out.println("3.240×320");
			System.out.print(">");
			line = reader.readLine().trim();
			if (line.equals("1") || line.equals("2") 
					|| line.equals("3") || line.equals("0")) {
				param.setDpx(ss[Integer.valueOf(line)]);
			} else {
				System.out.println("参数输入错误，请重新输入所有参数");
			}

//			/** 显示样式的类型 **/
//			private String stlye;
			ss = new String[]{
					"ZouMaDeng1", "ZouMaDeng2", "FlashColor1"
			};
			System.out.println("请输入显示样式的类型");
			System.out.println("0.走马灯（横屏）");
			System.out.println("1.走马灯（竖屏）");
			System.out.println("2.走马灯（彩色）");
			System.out.print(">");
			line = reader.readLine().trim();
			if (line.equals("1") || line.equals("0")
					|| line.equals("2")) {
				param.setStlye(ss[Integer.valueOf(line)]);
			} else {
				System.out.println("参数输入错误，请重新输入所有参数");
			}

//			/** 横竖屏标志 **/
//			private int hvFlag;
			int[] is = new int[]{
					Param.HVFLAG_HORIZONTAL,
					Param.HVFLAG_VERTICAL
			};
			System.out.println("请输入横竖屏标志");
			System.out.println("0.横屏");
			System.out.println("1.竖屏");
			System.out.print(">");
			line = reader.readLine().trim();
			if (line.equals("1") || line.equals("0")) {
				param.setHvFlag(is[Integer.valueOf(line)]);
			} else {
				System.out.println("参数输入错误，请重新输入所有参数");
			}

//			/** 文字 **/
//			private String s;
			System.out.println("请输入显示的文字");
			System.out.print(">");
			line = reader.readLine().trim();
			try {
				param.setS(line);
			} catch (Exception e) {
				System.out.println("参数输入错误，请重新输入所有参数");
			}

//			/** 字体大小 **/
//			private int size = 200;
			System.out.println("请输入字体大小");
			System.out.print(">");
			line = reader.readLine().trim();
			try {
				param.setSize(Integer.valueOf(line));
			} catch (Exception e) {
				System.out.println("参数输入错误，请重新输入所有参数");
			}

//			/** 米字屏总行数 **/
//			private int row = 1;
			System.out.println("请输入米字屏总行数");
			System.out.print(">");
			line = reader.readLine().trim();
			try {
				param.setRow(Integer.valueOf(line));
			} catch (Exception e) {
				System.out.println("参数输入错误，请重新输入所有参数");
			}

//			/** 米字屏总列数 **/
//			private int column = 2;
			System.out.println("请输入米字屏总列数");
			System.out.print(">");
			line = reader.readLine().trim();
			try {
				param.setColumn(Integer.valueOf(line));
			} catch (Exception e) {
				System.out.println("参数输入错误，请重新输入所有参数");
			}

//			/** 字体颜色 **/
//			private int fcolor;
			System.out.println("请输入字体颜色");
			System.out.println("0.白");
			System.out.println("1.黑");
			System.out.println("2.红");
			System.out.println("3.蓝");
			System.out.println("4.MI橙");
			System.out.println("5.Malata红");
			System.out.print(">");
			line = reader.readLine().trim();
			if (line.equals("1") || line.equals("2")
					|| line.equals("3") || line.equals("4")
					|| line.equals("5") || line.equals("0")) {
				param.setFcolor(Integer.valueOf(line));
			} else {
				System.out.println("参数输入错误，请重新输入所有参数");
			}

			
			System.out.println("请输入背景色");
			System.out.println("0.白");
			System.out.println("1.黑");
			System.out.println("2.红");
			System.out.println("3.蓝");
			System.out.println("4.MI橙");
			System.out.println("5.Malata红");
			System.out.print(">");
			line = reader.readLine().trim();
			if (line.equals("1") || line.equals("2")
					|| line.equals("3") || line.equals("4")
					|| line.equals("5") || line.equals("0")) {
				param.setBcolor(Integer.valueOf(line));
			} else {
				System.out.println("参数输入错误，请重新输入所有参数");
			}
//			/** 背景色 **/
//			private int bcolor;
		} else {
			System.out.println("服务已经启动，不能再修改参数");
		}
	}
	
	private void startServer() {
		if (serverThread == null) {
			connects = new ArrayList<Connect>();
			param.setStartFlag(true);
			serverThread = new ServerThread(param, connects);
			serverThread.start();
			System.out.println("服务启动成功");
		} else {
			System.out.println("服务已经启动");
		}
	}
	
	private void stopServer() {
		if (serverThread != null) {
			serverThread.stopServer();
			serverThread = null;
			param.setStartFlag(false);
			param.setGoFlag(false);
			System.out.println("服务已停止");
		} else {
			System.out.println("服务尚未启动");
		}
	}
	
	private void go() {
		if (serverThread != null) {
			if (param.getRow() * param.getColumn() <= connects.size()) {
				try {
					param.setGoFlag(true);
					assign();
					computeThread = new ComputeThread(param);
					computeThread.start();
					System.out.println("开始...");
				} catch (Exception e) {
					param.setGoFlag(false);
					computeThread = null;
					System.out.println("启动服务异常：" + e.getMessage());
				}
			} else {
				System.out.println("连接到服务器上的终端数量不够,当前连接数:" + connects.size());
			}
		} else {
			System.out.println("服务尚未启动");
		}
	}
	private void assign() throws Exception {
		Connect conn = null;
		int maxw = 0;
		int maxh = 0;
		for (Connect c : connects) {
			if (maxw < c.width) {
				maxw = c.width;
			}
			if (maxh < c.height) {
				maxh = c.height;
			}
		}
		for (int row = 0; row < param.getRow(); row++) {
			for (int colume = 0; colume < param.getColumn(); colume++) {
				conn = connects.get((row * param.getColumn()) + colume);
				conn.param = (Param) param.clone();
				conn.param.setMyRow(row);
				conn.param.setMyColumn(colume);
				conn.param.setWidth(maxw);
				conn.param.setHeight(maxh);
			}
		}
	}
	
	private void exit() {
		
		param.setRunFlag(false);
		System.exit(0);
	}
	
	private void showIP() {
		String ip = null;
		try {
			InetAddress addr = InetAddress.getLocalHost();
			ip = addr.getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		System.out.println(ip==null ? "未能取得本机IP" : "本机IP地址为：" + ip);
	}
	
	private void showHelp() {

//		public final static String CMD_HELP2 = "?";
//		public final static String CMD_HELP1 = "HELP";
//		public final static String CMD_SET_PARAM = "SET";
//		public final static String CMD_STOP = "STOP";
//		public final static String CMD_START_SERVER = "START";
//		public final static String CMD_GO = "GO";
//		public final static String CMD_IP = "IP";
//		public final static String CMD_EXIT = "EXIT";
		
		System.out.println("----------------------");
		System.out.println("* 帮助 *");
		System.out.println("----------------------");
		System.out.println("?或help：帮助");
		System.out.println("set：设置参数");
		System.out.println("stop：关闭服务");
		System.out.println("start：启动服务");
		System.out.println("go：客户端进入演示");
		System.out.println("n：查看连接客户端数量");
		System.out.println("ip：获知本机IP地址");
		System.out.println("port：设置服务端口");
		System.out.println("exit：退出");
		System.out.println("----------------------");
	}
}
